JavaScript Comma Operator (`,`)

Visualizing a little-known but powerful operator.

Evaluation and Return Value

The **comma operator** evaluates each of its operands from left to right and returns the value of the last operand. It is most commonly used in `for` loops to include multiple expressions in the initialization, condition, or increment sections.

let a = 1, b = 2; // Declaring and initializing multiple variables
for (let i = 0, j = 10; i < j; i++, j--) { /* ... */ }

let x = (10, 20); // x is now 20

Expression Evaluation Demo

Expression: (a = 10, b = 20, a + b)

Resulting variables after evaluation:

  • a:
  • b:

Return Value:


Common Use Case: `for` Loop

This is where the comma operator is most often seen. It allows for multiple expressions within a single statement, like initializing two loop counters at once.

let result = '';
for (let i = 0, j = 5; i < 3; i++, j--) {
  result += `i=${i}, j=${j} | `;
}

`for` Loop Demo

Execution Log: